//
//  HMMainController.swift
//  weibo10
//
//  Created by mac on 15/10/17.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit

class HMMainController: UITabBarController {
    // 按钮点击：加了private，如果不加 “@objc” 会崩溃
    @objc private func composeBtnClick(){
        let vc = HMUserAcountViewModel.sharedUserAccount.userLogon ? HMComposedController() : HMOAuthViewController()
        let nav = UINavigationController(rootViewController: vc)
        presentViewController(nav, animated: true, completion: nil)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        addChildViewControllers()
        // 此时打印tabBar.subviews，结果为空数组，原因：添加控制器并不会创建tabBar上的按钮，懒加载
        // print(tabBar.subviews)
        addComposeBtn()
    }
    override func viewWillAppear(animated: Bool) {
        // 会创建tabBar中得所有子控件
        super.viewWillAppear(true)
        // print(tabBar.subviews)
        tabBar.bringSubviewToFront(composeBtn)
    }
    // MARK -懒加载控件
    private lazy var composeBtn: UIButton = UIButton(imageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button")
}
// MARK -设置界面
extension HMMainController{
    // 添加“创建”按钮
    func addComposeBtn(){
        let count = childViewControllers.count
        // 容错，少缩点
        let w = tabBar.bounds.width / CGFloat(count) - 1
        composeBtn.frame = CGRectInset(tabBar.bounds, 2 * w, 0)
        tabBar.addSubview(composeBtn)
        // 给按钮添加点击方法
        composeBtn.addTarget(self, action: Selector("composeBtnClick"), forControlEvents: UIControlEvents.TouchUpInside)
    }
    // 添加多个控制器
    func addChildViewControllers() {
        
        addChildViewController(HMHomeController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(HMMessageController(), title: "消息", imageName: "tabbar_message_center")
        // 创建 “+”
        addChildViewController(UIViewController())
        
        addChildViewController(HMDiscoverController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(HMProfileController(), title: "我", imageName: "tabbar_profile")
    }
    // 添加控制器
    func addChildViewController(vc:UIViewController,title:String, imageName:String) {
        // 由内至外设置
        vc.title = title
//        // 渲染颜色
//        tabBar.tintColor = UIColor.orangeColor()
        vc.tabBarItem.image = UIImage(named: imageName)
        let nav = UINavigationController(rootViewController: vc)
        addChildViewController(nav)
    }
    
}

